package unibz.cn.gui;

import java.awt.Desktop;
import java.io.File;
import java.io.FileWriter;
import java.net.URI;


import javax.swing.JOptionPane;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.basic.DefaultOAuthConsumer;
import oauth.signpost.basic.DefaultOAuthProvider;
import oauth.signpost.signature.SignatureMethod;

import unibz.cn.logic.User;

public class RegistrationWindow extends javax.swing.JFrame {

	private static final String consumerKey = "7C6LburGp7wHAyy3gXYQ";
	private static final String consumerSecret = "bV40dZOxf4HEO9qHaz9QJ4V35N9AtNqJQ0hjX4eEVs";
	private OAuthConsumer consumer = new DefaultOAuthConsumer(consumerKey,consumerSecret,SignatureMethod.HMAC_SHA1);
	private OAuthProvider provider = new DefaultOAuthProvider(consumer,
            "http://twitter.com/oauth/request_token",
            "http://twitter.com/oauth/access_token",
            "http://twitter.com/oauth/authorize");
	private boolean checkPin = false;
	
    public RegistrationWindow() {
        initComponents();
    }


    private void initComponents() {

        usernameLabel = new javax.swing.JLabel();
        passwordLabel = new javax.swing.JLabel();
        rePasswordLabel = new javax.swing.JLabel();
        pincodeLabel = new javax.swing.JLabel();
        usernameTextField = new javax.swing.JTextField();
        jPasswordField1 = new javax.swing.JPasswordField();
        jPasswordField2 = new javax.swing.JPasswordField();
        pincodeTextField = new javax.swing.JTextField();
        getButton = new javax.swing.JButton();
        registerButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        setTitle("Registration Form");
        
        usernameLabel.setText("Username");

        passwordLabel.setText("password");

        rePasswordLabel.setText("retype psw");

        pincodeLabel.setText("pincode");

        getButton.setText("get");
        getButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	try {
					getButtonActionPerformed(evt);
				} catch (Exception e) {
					e.printStackTrace();
				}
            }
        });
        
        registerButton.setText("Register");
        registerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                try {
					registerButtonActionPerformed(evt);
				} catch (Exception e) {
					e.printStackTrace();
				}
            }
        });

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });
        
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(rePasswordLabel)
                            .addComponent(pincodeLabel))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPasswordField2)
                            .addComponent(pincodeTextField)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(passwordLabel)
                            .addComponent(usernameLabel))
                        .addGap(24, 24, 24)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(usernameTextField)
                            .addComponent(jPasswordField1))))
                .addGap(18, 18, 18)
                .addComponent(getButton, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18))
            .addGroup(layout.createSequentialGroup()
                .addGap(46, 46, 46)
                .addComponent(registerButton)
                .addGap(40, 40, 40)
                .addComponent(cancelButton)
                .addContainerGap(79, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(usernameLabel)
                    .addComponent(usernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passwordLabel)
                    .addComponent(jPasswordField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(rePasswordLabel)
                    .addComponent(jPasswordField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(pincodeLabel)
                    .addComponent(pincodeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(getButton))
                .addGap(36, 36, 36)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(registerButton)
                    .addComponent(cancelButton))
                .addContainerGap(26, Short.MAX_VALUE))
        );

        pack();
    }

    private void getButtonActionPerformed(java.awt.event.ActionEvent evt) throws Exception{
    	String authUrl = provider.retrieveRequestToken(OAuth.OUT_OF_BAND);
    	Desktop.getDesktop().browse(new URI(authUrl));
    	checkPin = true;
    }
    
    private void registerButtonActionPerformed(java.awt.event.ActionEvent evt) throws Exception{
    	String username = usernameTextField.getText();
    	String password = jPasswordField1.getText();
    	SAXReader reader = new SAXReader();
    	if (!User.checkUser(username, password) && checkPin) {
    		if (jPasswordField1.getText().equals(jPasswordField2.getText())) {
			User.addUser(username, password);
			String pin = pincodeTextField.getText();
	        provider.retrieveAccessToken(pin);
	        Document document = reader.read(new java.io.File(".").getCanonicalPath()+"/users.xml");
	        Element element = (Element)document.selectSingleNode("/users/user[username=\""+username+"\"]/accesstoken");
	        element.setText(consumer.getToken());
	        element = (Element)document.selectSingleNode("/users/user[username=\"" +username+ "\"]/tokensecret");
	        element.setText(consumer.getTokenSecret());
	        XMLWriter output = new XMLWriter( new FileWriter( new File(new java.io.File(".").getCanonicalPath()+"/users.xml") ));
		    output.write( document );
		    output.close();
		    this.dispose();
	    	java.awt.EventQueue.invokeLater(new Runnable() {
	            public void run() {
	                new LoginWindow().setVisible(true);
	            }
	        });
    		} else JOptionPane.showMessageDialog(null,"The 2 passwords are not equals", "Attention",JOptionPane.ERROR_MESSAGE);
		} else {
			if (checkPin)
				JOptionPane.showMessageDialog(null,"Nickname already present", "Attention",JOptionPane.ERROR_MESSAGE);
			else
				JOptionPane.showMessageDialog(null,"Incorrect pin", "Attention",JOptionPane.ERROR_MESSAGE);
		}	  
    }
    
    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {
    	java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LoginWindow().setVisible(true);
            }
        });   
    	this.dispose();
    }

    // Variables declaration - do not modify
    private javax.swing.JButton getButton;
    private javax.swing.JButton registerButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel usernameLabel;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JLabel rePasswordLabel;
    private javax.swing.JLabel pincodeLabel;
    private javax.swing.JPasswordField jPasswordField1;
    private javax.swing.JPasswordField jPasswordField2;
    private javax.swing.JTextField usernameTextField;
    private javax.swing.JTextField pincodeTextField;
    // End of variables declaration

}

